package com.mydemo.sftp.pool2;

import com.mydemo.sftp.SftpClient;
import com.mydemo.sftp.SftpProperty;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;

public class SftpClientPooledObjectFactory implements PooledObjectFactory<SftpClient> {

    private SftpProperty sftpProperty;

    @Override
    public PooledObject<SftpClient> makeObject() throws Exception {
        return new DefaultPooledObject<>(new SftpClient());
    }

    @Override
    public void destroyObject(PooledObject<SftpClient> p) throws Exception {
        SftpClient object = p.getObject();
        if (object != null){
            object.disconnect();
        }
    }

    @Override
    public boolean validateObject(PooledObject<SftpClient> p) {
        SftpClient object = p.getObject();
        if (object != null){
            return true;
        }
        return false;
    }

    @Override
    public void activateObject(PooledObject<SftpClient> p) throws Exception {
        SftpClient object = p.getObject();
        if (object != null){
            object.init(sftpProperty);
        }
    }

    @Override
    public void passivateObject(PooledObject<SftpClient> p) throws Exception {
        SftpClient object = p.getObject();
        object.reset();
    }

    public void setSftpProperty(SftpProperty sftpProperty) {
        this.sftpProperty = sftpProperty;
    }
}
